<?php namespace modules\user;
/**
 * @subpackage  \modules\user
 *
 * @copyright   Copyright (C) 2013 - 2014 Mailerm, Inc. All rights reserved.
 */

# Load Libraries
require_once MPATH_LIBRARIES . '/log4php/Logger.php';
require_once MPATH_LIBRARIES . '/captcha/Captcha.php';

use \Logger as Logger;
use \Captcha as Captcha;

# Load Configuration
require_once MPATH_MODULES . '/configuration.php';

# Load Models
require_once MPATH_MODULES . '/shared/model_user.php';
require_once MPATH_MODULES . '/shared/model_project.php';

use \shared\model\user as User;
use \shared\model\project as Project;

Logger::configure(dirname(__FILE__) . '/log4php.properties');

$logger = Logger::getRootLogger();

// User Login...
// 0:登陆成功
// 1:输入信息有误
// 2:验证码错误
// 3:用户名或密码错误
// 4:服务器异常
// 5:项目暂停
// 6:项目筹备中
// 7:项目已结束
function login ($params, $method, $app) {
    $app->require_method('post');
	$result = array();
    if (!isset($params['captcha']) || !isset($params['account']) || !isset($params['password']) || empty($params['captcha']) || empty($params['account']) || empty($params['password'])) {
    	$result['status'] = 1;
    	$app->return_json($result);
    	exit();
    }
    // Check Cpptcha
    session_start();
    if (!isset($_SESSION[SESSION_CAPTCHA_USER]) || $_SESSION[SESSION_CAPTCHA_USER] != $params['captcha']) {
    	unset($_SESSION[SESSION_CAPTCHA_USER]);
    	$result['status'] = 2;
    	$app->return_json($result);
    	exit();
    }
    unset($_SESSION[SESSION_CAPTCHA_USER]);
    $account = $params['account'];
    // Find User
    $user = User\get_by_account($account);
    if ($user == null) {
        $result['status'] = 3;
        $app->return_json($result);
        exit();
    }

    // Check User Status
    if (!isset($user['status']) || $user['status'] != USER_STATUS_NORMAL) {
        $result['status'] = 3;
        $app->return_json($result);
        exit(); 
    }
    // Check Password
    if (!isset($user['password']) || empty($user['password']) || !isset($user['role'])) {
        $result['status'] = 4;
        $app->return_json($result);
        exit(); 
    }
    // Check Project
    if ($user['role'] == ROLE_MATERIAL || $user['role'] == ROLE_WORKER) {
        if ($user['project'] < 1) {
            $result['status'] = 4;
            $app->return_json($result);
            exit(); 
        }
        $project = Project\get($user['project']);
        if ($project == null) {
            $result['status'] = 3;
            $app->return_json($result);
            exit();
        }
        // Check project status
        if ($project['status'] == PROJECT_STATUS_PAUSED) {
            $result['status'] = 5;
            $app->return_json($result);
            exit();
        } else if ($project['status'] != PROJECT_STATUS_NORMAL) {
            $result['status'] = 4;
            $app->return_json($result);
            exit(); 
        }
        // Check project process
        if ($project['process'] == PROJECT_PROCESS_PREPARE) {
            $result['status'] = 6;
            $app->return_json($result);
            exit();
        } else if ($project['process'] == PROJECT_PROCESS_FINISHED) {
            $result['status'] = 7;
            $app->return_json($result);
            exit();
        } else if ($project['process'] != PROJECT_PROCESS_ONGOING) {
            $result['status'] = 4;
            $app->return_json($result);
            exit(); 
        }
    }
    $tmp = explode(':', $user['password']);
    if (count($tmp) != 2) {
        $result['status'] = 4;
        $app->return_json($result);
        exit(); 
    }
    $hash = $tmp[0];
    $salt = $tmp[1];
    if (substr(sha1(md5($params['password']) . $salt), 0, 32) === $hash) {
        // update login infor
        User\execute('UPDATE `' . TBL_USER . '` SET `login_time`=\'' . date(FORMAT_DATE) . '\', `login_ip`=\'' . $app->client_ip() . '\' WHERE `account`=\'' . $account . '\'');
        unset($user['password']);
        $_SESSION[SESSION_USER_INFO] = $user;
        $result['status'] = 0;
        $app->return_json($result);
        exit();
    } else {
        $result['status'] = 3;
        $app->return_json($result);
        exit(); 
    }
}

// change user password
// 0:修改成功
// 1:输入信息有误
// 3:密码错误
// 4:服务器异常
function passwd($params, $method, $app) {
    // Check Role
    if (!_user_belong(array(ROLE_MANAGER, ROLE_PLANNER, ROLE_BUYER, ROLE_SUMMARY, ROLE_MATERIAL, ROLE_WORKER))) {
        $app->return_error(403, 'Forbidden', 'You don\'t have permission to access this server.');
        exit();
    }
    // Check params
    $current = isset($params['current']) ? $params['current'] : '';
    $password = isset($params['password']) ? $params['password'] : '';
    if (empty($current) || empty($password)) {
        $result['status'] = 1;
        $app->return_json($result);
        exit();
    }
    // Find user
    $account = $_SESSION[SESSION_USER_INFO]['account'];
    $user = User\get_by_account($account);
    if ($user == null) {
        $result['status'] = 4;
        $app->return_json($result);
        exit(); 
    }
    // Check current password
    $tmp = explode(':', $user['password']);
    if (count($tmp) != 2) {
        $result['status'] = 4;
        $app->return_json($result);
        exit(); 
    }
    $hash = $tmp[0];
    $salt = $tmp[1];
    if (substr(sha1(md5($current) . $salt), 0, 32) === $hash) {
        $salt = md5(_rand_string(5));
        $password = substr(sha1(md5($password) . $salt), 0, 32) . ':' . $salt;
        $database = User\execute('UPDATE `' . TBL_USER . '` SET `password`=\'' . $password . '\' WHERE `id`=' . $user['id']);
        $result['status'] = $database->affected_rows() < 0 ? 4 : 0;
        $app->return_json($result);
        exit(); 
    } else {
        $result['status'] = 3;
        $app->return_json($result);
        exit(); 
    }
}

// get login user info
// 0:获取成功
// 4:服务器异常
function info($params, $method, $app) {
    $result = array();
    session_start();
    if (!isset($_SESSION[SESSION_USER_INFO])) {
        $app->return_error(403, 'Forbidden', 'You don\'t have permission to access this server.');
        exit();
    } else {
        $result['status'] = 0;
        $result['user'] = $_SESSION[SESSION_USER_INFO];
        $app->return_json($result);
        exit();
    }
}

// Get User Detail
// 0:获取成功
// 1:用户未找到
// 4:服务器异常
function detail($params, $method, $app) {
    $app->require_method('post');
    // Check Role
    if (!_user_belong(array(ROLE_MANAGER))) {
        $app->return_error(403, 'Forbidden', 'You don\'t have permission to access this server.');
        exit();
    }
    $id = isset($params['id']) ? $params['id'] : '';
    if (trim($id) == '') {
        $result['status'] = 1;
        $app->return_json($result);
        exit();
    }
    // Get User
    $user = User\get($id);
    if ($user == null) {
        $result['status'] = 1;
        $app->return_json($result);
        exit(); 
    }   
    // Check User Status
    if (!isset($user['status']) || $user['status'] == USER_STATUS_DELETED) {
        $result['status'] = 1;
        $app->return_json($result);
        exit(); 
    } else {
        $result['status'] = 0;
        $result['user'] = $user;
        $app->return_json($result);
        exit();
    }
}

// user logout
function logout ($params, $method, $app) {
    session_start();
    unset($_SESSION[SESSION_USER_INFO]);
    exit(); 
}

// get user mod captcha
function captcha($params, $method, $app) {
	session_start();
	$captcha = new Captcha();
	$captcha->set_image_size(90, 30);
	$val = $captcha->gen_value(4);
	$_SESSION[SESSION_CAPTCHA_USER] = $val;
	$captcha->return_image();
}

// Add User
// 0:添加成功
// 1:输入信息有误
// 2:项目不可用
// 3:
// 4:服务器异常
// 5:角色存在不可添加
function project_add($params, $method, $app) {
    $app->require_method('post');
    // Check Role
    if (!_user_belong(array(ROLE_MANAGER))) {
        $app->return_error(403, 'Forbidden', 'You don\'t have permission to access this server.');
        exit();
    }
    $result = array();
    $roles = array( ROLE_MATERIAL, ROLE_WORKER );
    $salt = md5(_rand_string(5));
    $password = substr(sha1(md5(DEFAULT_USER_PASS) . $salt), 0, 32) . ':' . $salt;
    $role = isset($params['role']) ? $params['role'] : -1;
    if (!in_array($role, $roles)) {
        $result['status'] = 1;
        $app->return_json($result);
        exit();
    }
    // Check project
    $project = isset($params['project']) ? $params['project'] : -1;
    if ($project == -1) {
        $result['status'] = 1;
        $app->return_json($result);
        exit();
    }
    $project = Project\get($project);
    if ($project == null) {
        $result['status'] = 2;
        $app->return_json($result);
        exit();
    }

    $status = USER_STATUS_NORMAL;
    $create_time = date(FORMAT_DATE) ;
    $update_time = DEFAULT_DATE;
    $login_time = DEFAULT_DATE;
    $login_ip = '';
    
    # Make Account
    do {
        $account = rand(10000, 999999);
        $user = User\get_by_account($account);
    } while ($user != null);
    
    // Check user role
    $users = User\get_by_project($project['id'], $role);
    if (count($users) > 0) {
        $result['status'] = 5;
        $app->return_json($result);
        exit();
    }

    if (User\save($project['id'], $account, $password, $role, $status, $create_time, $update_time, $login_time, $login_ip) < 0) {
        $result['status'] = 4;
        $result['msg'] = '账号保存失败！';
        $app->return_json($result);
        exit();
    } else {
        $result['status'] = 0;
        $result['account'] = $account;
        $app->return_json($result);
        exit();
    }
}

// Add User
// 0:添加成功
// 1:输入信息有误
// 2:项目不可用
// 3:
// 4:服务器异常
function add($params, $method, $app) {
    $app->require_method('post');
    // Check Role
    if (!_user_belong(array(ROLE_MANAGER))) {
        $app->return_error(403, 'Forbidden', 'You don\'t have permission to access this server.');
        exit();
    }
    $result = array();
    $roles = array(
                ROLE_PLANNER, 
                ROLE_BUYER, 
                ROLE_SUMMARY
            );  // 1 root is not allowed
    $salt = md5(_rand_string(5));
    $password = substr(sha1(md5(DEFAULT_USER_PASS) . $salt), 0, 32) . ':' . $salt;
    $role = isset($params['role']) ? $params['role'] : -1;
    if (!in_array($role, $roles)) {
        $result['status'] = 1;
        $app->return_json($result);
        exit();
    }
    $project = 0;
    $status = USER_STATUS_NORMAL;
    $create_time = date(FORMAT_DATE) ;
    $update_time = DEFAULT_DATE;
    $login_time = DEFAULT_DATE;
    $login_ip = '';
    
    # Make Account
    do {
        $account = rand(10000, 999999);
        $user = User\get_by_account($account);
    } while ($user != null);
    
    if (User\save($project, $account, $password, $role, $status, $create_time, $update_time, $login_time, $login_ip) < 0) {
        $result['status'] = 4;
        $result['msg'] = '账号保存失败！';
        $app->return_json($result);
        exit();
    } else {
        $result['status'] = 0;
        $result['account'] = $account;
        $app->return_json($result);
        exit();
    }
}

// Active User
// 0:操作成功
// 1:输入信息有误
// 4:服务器异常
function active($params, $method, $app) {
    $app->require_method('post');
    // Check Role
    if (!_user_belong(array(ROLE_MANAGER))) {
        $app->return_error(403, 'Forbidden', 'You don\'t have permission to access this server.');
        exit();
    }
    $current_user = $_SESSION[SESSION_USER_INFO];
    $ids = isset($params['ids']) ? $params['ids'] : '';
    if (trim($ids) == '') {
        $result['status'] = 1;
        $app->return_json($result);
        exit();
    }
    $tmp = explode(',', $ids);
    $ids = array();
    foreach ($tmp as $k => $v) $ids[] = intval($v);
    if (empty($ids)) {
        $result['status'] = 0;
        $result['affect'] = 0;
        $app->return_json($result);
        exit();   
    }
    // Ban
    $affect = User\active($ids, $current_user['id']);
    # Check Result
    $result['status'] = 0;
    $result['affect'] = $affect;
    $app->return_json($result);
    exit();
}

// Ban User
// 0:操作成功
// 1:输入信息有误
// 4:服务器异常
function ban($params, $method, $app) {
    $app->require_method('post');
    // Check Role
    if (!_user_belong(array(ROLE_MANAGER))) {
        $app->return_error(403, 'Forbidden', 'You don\'t have permission to access this server.');
        exit();
    }
    $current_user = $_SESSION[SESSION_USER_INFO];
    $ids = isset($params['ids']) ? $params['ids'] : '';
    if (trim($ids) == '') {
        $result['status'] = 1;
        $app->return_json($result);
        exit();
    }
    $tmp = explode(',', $ids);
    $ids = array();
    foreach ($tmp as $k => $v) $ids[] = intval($v);
    if (empty($ids)) {
        $result['status'] = 0;
        $result['affect'] = 0;
        $app->return_json($result);
        exit();   
    }
    // Ban
    $affect = User\ban($ids, $current_user['id']);
    # Check Result
    $result['status'] = 0;
    $result['affect'] = $affect;
    $app->return_json($result);
    exit();
}

// Delete User
// 0:操作成功
// 1:输入信息有误
// 4:服务器异常
function delete($params, $method, $app) {
    $app->require_method('post');
    // Check Role
    if (!_user_belong(array(ROLE_MANAGER))) {
        $app->return_error(403, 'Forbidden', 'You don\'t have permission to access this server.');
        exit();
    }
    $current_user = $_SESSION[SESSION_USER_INFO];
    $ids = isset($params['ids']) ? $params['ids'] : '';
    if (trim($ids) == '') {
        $result['status'] = 1;
        $app->return_json($result);
        exit();
    }
    $tmp = explode(',', $ids);
    $ids = array();
    foreach ($tmp as $k => $v) $ids[] = intval($v);
    if (empty($ids)) {
        $result['status'] = 0;
        $result['affect'] = 0;
        $app->return_json($result);
        exit();   
    }
    // Delete
    $affect = User\delete($ids, $current_user['id']);
    # Check Result
    $result['status'] = 0;
    $result['affect'] = $affect;
    $app->return_json($result);
    exit();
}

// find users
function find($params, $method, $app) {
    // Check Role
    if (!_user_belong(array(ROLE_MANAGER))) {
        $app->return_error(403, 'Forbidden', 'You don\'t have permission to access this server.');
        exit();
    }
    $start = isset($params['iDisplayStart']) ? intval($params['iDisplayStart']) : 0;
    $size = isset($params['iDisplayLength']) ? intval($params['iDisplayLength']) : 10;
    $project = isset($params['project']) ? intval($params['project']) : 0;
    $result = array();
    $result['sEcho'] = isset($params['sEcho']) ? intval($params['sEcho']) : 1;
    # Count users
    $total = User\count($project);
    if ($total < 1) {
        $result['iTotalRecords'] = 0;
        $result['iTotalDisplayRecords'] = 0;
        $result['aaData'] = array();
        $app->return_json($result);
        exit(); 
    }
    # Find Page
    $users = User\find($project, $start, $size);
    # Num Rows
    if(count($users) < 1) {
        $result['iTotalRecords'] = 0;
        $result['iTotalDisplayRecords'] = 0;
        $result['aaData'] = array();
        $app->return_json($result);
        exit();
    }
    $result = array();
    $result['sEcho'] = intval($params['sEcho']);
    $result['iTotalRecords'] = $total;
    $result['iTotalDisplayRecords'] = $total;
    $result['aaData'] = array();
    foreach ($users as $key => $user) {
        $row = array();
        foreach ($user as $key => $value) $row[] = $value;
        $result['aaData'][] = $row;
    }

    $app->return_json($result);
    exit();
}

// check is user role match
function _user_belong($roles) {
    session_start();
    if (!isset($_SESSION[SESSION_USER_INFO])) return false;
    if (!isset($roles) || empty($roles) || count($roles) == 0) return true;
    if (!isset($_SESSION[SESSION_USER_INFO]['role'])) {
        unset($_SESSION[SESSION_USER_INFO]);
        return false;
    } else {
        return in_array($_SESSION[SESSION_USER_INFO]['role'], $roles);
    }
}

// rand string
function _rand_string( $length ) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';  
    $str = '';
    $size = strlen( $chars );
    for( $i = 0; $i < $length; $i++ ) {
        $str .= $chars[ rand( 0, $size - 1 ) ];
    }
    return $str;
}